<template>
<div>
  <!-- 左侧指标体系列表 -->
    <div style="height:300px;width:400px;overflow-y:auto">
          <el-card class="box-card">
            <el-table :data="indexSystemListData" stripe style="width: 150%">
        <el-table-column prop="indexSystemName" label="已有指标体系" width="200"></el-table-column>
        <el-table-column  label="" width="100">
          <template v-slot="scope">
        <el-button @click="findIndexSystemByName(scope.row.name)" type="text" size="small">查看</el-button>
          </template>
    </el-table-column>
             </el-table>
          </el-card>
      </div>
      <!-- 左侧待选指标列表 -->
      <div style="height:300px;width:400px;overflow-y:auto;marginTop:10px">
          <el-card class="box-card">
            待选指标
            <el-table :data="userData.userList" stripe style="width: 100%" border>
              <el-table-column prop="mes" label="指标名"></el-table-column>
            </el-table>
          </el-card>
      </div>
      <!-- 指标体系库中的相关属性 -->
      <div class="header">
          <span>体系名称</span><input type="text" style="marginRight:20px" v-model="systemName">
          <span>制定人</span><input type="text" style="marginRight:20px" :disabled="edit">
          <span>制定时间</span><input type="text" style="marginRight:20px" :disabled="edit">
      </div>
      <!-- 指标体系树实现 -->
      <div class="container bxs" style="width:40%;position:absolute;top:20%;left:45%">
    <div class="ct-inner bxs">
      <div class="ct-inner-fiexd w">
        <div class="w clearfix tc mt10">
          <el-button class="fll" type="primary" plain size="mini">刷新</el-button>
          <el-button type="primary" plain size="mini" @click="unFoldAll">全部展开</el-button>
          <el-button class="flr" type="primary" plain size="mini" @click="collapseAll">全部收起</el-button>
        </div>
      </div>
      <div class="ct-inner-content h">
        <!-- show-checkbox 是否展示多选框 -->
        <!-- :check-on-click-node="true" 点击文本内容是否选中 -->
        <el-tree
          v-if="openOrNot"
          :data="treeData"
          node-key="id"
          :default-expand-all="defaultExpand"
          :expand-on-click-node="false"
          @node-click="handleLeftclick"
          @node-drag-start="handleDragStart"
          @node-drag-enter="handleDragEnter"
          @node-drag-leave="handleDragLeave"
          @node-drag-over="handleDragOver"
          @node-drag-end="handleDragEnd"
          @node-drop="handleDrop"
          @node-contextmenu="rightClick"
          :filter-node-method="filterNode"
          draggable
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          ref="tree"
        >
          <span class="slot-t-node span-ellipsis" slot-scope="{ node, data }">
            <span class="span-ellipsis-inner" v-show="!data.isEdit">
              <!-- <el-tooltip class="item" effect="dark" :content="node.label" placement="right"> -->
              <span class="span-ellipsis">
                <span
                  class="span-ellipsis"
                  :class="[(selectTreeData&&data.id==selectTreeData.id)? 'slot-t-node--label' : '']"
                  style="vertical-align:middle;"
                >
                  <i class="iconfont jxintegral-fill"></i>
                  {{node.label}}
                </span>
              </span>
              <!-- </el-tooltip> -->
            </span>
            <!-- autofocus -->
            <span v-show="data.isEdit">
              <el-input
                class="slot-t-input"
                style="height:28px;"
                size="mini"
                v-model="data.label"
                :ref="'slotTreeInput'+data.id"
                @blur.stop="NodeBlur(node,data)"
                @keydown.native.enter="NodeBlur(node,data)"
              ></el-input>
            </span>
          </span>
        </el-tree>

        <el-card class="box-card" ref="card" v-show="menuVisible">
          <div @click="addSameLevelNode()" v-show="firstLevel">
            <i class="el-icon-circle-plus-outline"></i>
            <span class="ml10">同级增加</span>
          </div>
          <div class="add">
            <i class="el-icon-circle-plus-outline" ></i>
            <span class="ml10" @click="addDialogVisible = true">子级增加</span>
          </div>
          <div class="delete" @click="deleteNode()">
            <i class="el-icon-remove-outline"></i>
            <span class="ml10">删除节点</span>
          </div>
          <div class="edit" @click="editNode()">
            <i class="el-icon-edit"></i>
            <span class="ml10">修改节点</span>
          </div>
        </el-card>
         <!-- 添加节点对话框 -->
    <el-dialog title="添加指标" :visible.sync="addDialogVisible" width="30%" @close="addDislogClosed">
      <!-- 内容主题区域 -->
        <el-select v-model="value" filterable placeholder="请选择" @change="selectName(value)">
        <el-option
          v-for="item in userData.userList"
          :key="item.id"
          :label="item.mes"
          :value="item">
        </el-option>
       </el-select>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addChildNode">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改节点对话框 -->
     <el-dialog title="修改指标" :visible.sync="editDialogVisible" width="30%" @close="addDislogClosed">
      <!-- 内容主题区域 -->
        <el-select v-model="value" filterable placeholder="请选择" @change="selectName(value)">
        <el-option
          v-for="item in userData.userList"
          :key="item.id"
          :label="item.mes"
          :value="item.mes">
        </el-option>
       </el-select>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editNode">确 定</el-button>
      </span>
    </el-dialog>
      </div>
    </div>
  </div>
    <!-- 对页面进行相关操作 -->
<div class="buttons">
    <el-button type="primary" @click="addNewTixi">新建</el-button>
    <el-button>修改</el-button>
    <el-button>删除</el-button>
    <el-button type="primary" @click="preserveNewTixi">保存</el-button>
    <el-button>返回</el-button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
  name: 'PersonManageLf',
  components: {},
  data() {
    return {
      openOrNot: true, // 展开收缩dom挂载切换
      defaultExpand: true, // 默认全部展开
      eleId: '',
      isShow: false,
      currentData: '',
      currentNode: '',
      menuVisible: false,
      firstLevel: false,
      // 设置输入框是否可编辑
      edit: true,
      filterText: '',
      maxexpandId: 4,
      userData: {
        userList: [],
        total: 0
      },
      treedataArray: [
        {
          id: -1,
          label: '',
          parentId: -1
        }
      ],
      // 新建指标体系名
      systemName: '',
      // 指标体系名
      indexSystemListData: [],
      // 新添加的指标名
      addNoreName: '',
      // 转化的一维数组
      newArr: {
        id: -1,
        label: '',
        pid: -1
      },
      // 存储新建指标体系的信息
      addForm: {
        name: ''

      },
      // 控制添加指标对话框的显示和隐藏
      addDialogVisible: false,
      treeData:
        [
          {
            id: '',
            label: '请输入指标体系名',
            pid: '',
            indexId: '',
            children: [
            ]
          }
        ],
      treeDataCopy: '', //   拖拽结束后验证后不可拖拽
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      indexId: '',
      dataList: [{
      }],
      selectTreeNode: '', // 选中的树节点，内含父节点
      selectTreeData: '', // 选中的树data
      newAddTreeObjs: {}, // 新增节点储存对象
      nowAddTreeNodeid: '', // 当前新增节点id
      data: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      },
      {
        id: 2,
        label: '一级 2',
        children: [{
          id: 5,
          label: '二级 2-1'
        }, {
          id: 6,
          label: '二级 2-2'
        }]
      },
      {
        id: 3,
        label: '一级 3',
        children: [{
          id: 7,
          label: '二级 3-1'
        }, {
          id: 8,
          label: '二级 3-2'
        }]
      }]
    }
  },
  created() {
    this.getUserList() // 获取待选指标
    this.getindexSystemList() // 获取指标体系名单
  },
  methods: {
    // 获取数据库中的指标
    async getUserList() {
      const { data: res } = await this.$http.get('/evaluate/normmes/list', {
        params: this.queryInfo
      })
      this.userData.userList = res.page.list
      this.userData.total = res.page.totalCount
      if (res.code !== 0) {
        this.$message.error('获取用户列表失败!')
      }
      this.$message.success('获取用户列表成功!')
    },
    // 下拉框中所选中的指标名称
    selectName(item) {
      this.name = item.name
      this.indexId = item.id
      this.$forceUpdate() // 强制刷新
    },
    // 全部展开
    unFoldAll() {
      const self = this
      // 将没有转换成树的原数据
      const list = this.treeData
      for (let i = 0; i < list.length; i++) {
        // 将没有转换成树的原数据设置key为... 的展开
        self.$refs.tree.store.nodesMap[list[i].id].expanded = true
      }
    },
    // 全部折叠
    collapseAll() {
      const self = this
      // 将没有转换成树的原数据
      const list = this.treeData
      for (let i = 0; i < list.length; i++) {
        self.$refs.tree.store.nodesMap[list[i].id].expanded = false
      }
    },
    renderContent(h, { node, data, store }) {
      console.log(node.label)
      console.log(data)
      console.log(store)
      return (
        <div style="display:inline-block;">
          <span style="">{node.label}</span>
        </div>
      )
    },
    open() {
      this.defaultExpand = !this.defaultExpand
      this.openOrNot = false
      setTimeout(() => {
        this.openOrNot = true
      }, 10)
    },

    NodeBlur(Node, data) {
      // debugger;
      console.log(Node, data)
      if (data.label.length === 0) {
        this.$message.error('菜单名不可为空！')
        return false
      } else {
        if (data.isEdit) {
          this.$set(data, 'isEdit', false)
          console.log(data.isEdit)
        }
        this.$nextTick(() => {
          this.$refs['slotTreeInput' + data.id].$refs.input.focus()
        })
      }
    },
    // 查询
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleDragStart(node, ev) {
      console.log(this.treeData, '树')
      console.log('drag start', node)
      //   如果要阻止拖拽
      //   if(node.childNodes.length>0){
      //       console.log("有子节点不能移动")
      //       ev.preventDefault();
      //       return;
      //   }
    },
    handleDragEnter(draggingNode, dropNode, ev) {
      console.log('tree drag enter: ', dropNode.label)
    },
    handleDragLeave(draggingNode, dropNode, ev) {
      console.log('tree drag leave: ', dropNode.label)
    },
    handleDragOver(draggingNode, dropNode, ev) {
      console.log('tree drag over: ', dropNode.label)
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log('tree drag end: ', dropNode && dropNode.label, dropType)
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', dropNode.label, dropType)
      //   拖拽结束后验证后不可拖拽
      //    console.log(this.treeData,'树')
      //    this.treeData=JSON.parse(JSON.stringify(this.treeDataCopy));
    },
    allowDrop(draggingNode, dropNode, type) {
      console.log(dropNode.data)
      if (dropNode.data.label === '二级 3-1') {
        return type !== 'inner'
      } else {
        return true
      }
    },
    allowDrag(draggingNode) {
      return draggingNode.data.label.indexOf('三级 3-2-2') === -1
    },
    // 鼠标右击事件
    rightClick(MouseEvent, object, Node, element) {
      //   debugger;
      console.log(Node)
      this.currentData = object
      this.currentNode = Node
      if (Node.level === 1) {
        this.firstLevel = true
      } else {
        this.firstLevel = false
      }
      this.menuVisible = true // let menu = document.querySelector('#card')
      // /* 菜单定位基于鼠标点击位置 */
      // menu.style.left = event.clientX + 'px'
      // menu.style.top = event.clientY + 'px'
      document.addEventListener('click', this.foo)
      // console.log(event.clientY);
      this.$refs.card.$el.style.left = event.clientX + 40 - 250 + 'px'
      this.$refs.card.$el.style.top = event.clientY + 10 - 165 + 'px'
    },
    // 鼠标左击事件
    handleLeftclick(data, node) {
      // console.log(data,'选中的节点')
      this.selectTreeNode = node
      this.selectTreeData = data
      this.foo(data.id, true)
    },
    // 保存点击事件
    preserveNewTixi() {
      // 数组转换
      var copydata = this.deepCopy(this.treeData)
      var bb = this.jsonToArray(copydata)
      const resdata = JSON.parse(JSON.stringify(bb))
      this.dataList = resdata
      // 传递数组到后台
      this.sendTreeData()
    },
    // 判断是否为新增id，且新增id是否为真id
    sureNewOrOld(id) {
      // 1 表明是旧id，2表示新id，3表示id未返回
      id = id + ''
      const arrs = id.split('-')
      const newAddTreeObjs = this.newAddTreeObjs
      if (arrs[0] === 'xzjd') {
        console.log(id)
        console.log(newAddTreeObjs)
        console.log(newAddTreeObjs[id])
        const idData = newAddTreeObjs[id]
        if (idData.id !== id) {
          return 2
        } else {
          // 新增部门，请刷新列表获取信息！
          this.$message.warning('新增部门，请稍后操作！')
          this.selectTreeNode = ''
          this.selectTreeData = ''
          return 3
        }
      } else {
        return 1
      }
    },
    //  取消鼠标监听事件 菜单栏
    foo(id, havesure) {
      // havesure判断是否为左键点击
      const newAddTreeObjs = this.newAddTreeObjs
      this.menuVisible = false //  要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
      document.removeEventListener('click', this.foo)
      if (this.nowAddTreeNodeid) {
        this.nowAddTreeNodeid = ''
        return
      }
      console.log('真正选中的节点')
      if (!havesure) {
        return
      }
      const oldSure = this.sureNewOrOld(id)
      console.log(oldSure)
      if (oldSure === 2) {
      } else if (oldSure === 3) {
        return
      } else {
        this.changeRightMess(id)
      }
      console.log()
    },
    // 刷新右侧信息
    changeRightMess(id) {
      this.$emit('sentFather', { id: id })
    },
    // 增加同级节点事件
    addSameLevelNode() {
      let id = Math.ceil(Math.random() * 1000)
      const timestamp = Date.parse(new Date())
      id = 'xzjd-' + id + '-' + timestamp
      console.log(id)
      var data = { id: id, label: '新增节点' }
      this.newAddTreeObjs[id] = data
      this.nowAddTreeNodeid = id
      this.$refs.tree.append(data, this.currentNode.parent)
    },
    // 增加子级节点事件
    addChildNode() {
      console.log(this.currentData)
      console.log(this.currentNode)
      const id = Math.ceil(Math.random() * 1000) // 新节点ID
      const pid = this.currentNode.id // 新节点的父ID
      var data = { id: id, label: this.name, indexId: this.indexId, pid: pid }
      this.newAddTreeObjs[id] = data
      this.nowAddTreeNodeid = id
      this.$refs.tree.append(data, this.currentNode) // 添加到treeData
      this.treedataArray.id = this.nowAddTreeNodeid
      // 关闭对话框
      this.addDialogVisible = false
    },
    // 传递指标树数据到后台
    async sendTreeData() {
      const { data: res } = await this.$http.post('/index/system/get', { sys: this.dataList, name: this.systemName }
      )
      if (res.code === 0) {
        return this.$message.success('指标体系保存成功~')
      } else { return this.$message.error('指标体系保存失败了~') }
    },
    // 指标体系信息
    async addNewTixi() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 可以发起添加指标请求
        const { data: res } = await this.$http.post('/generator/indexMes/add', this.addForm)
        if (res.code !== 0) {
          return this.$message.error('指标体系信息添加失败了~')
        }
        // 指标重置
        this.treeData = this.data
        return this.$message.success('指标体系信息添加成功了~')
      })
    },
    // 获取已上传指标体系名单
    async getindexSystemList() {
      const { data: res } = await this.$http.get('/index/system/findbyid')
      this.indexSystemListData = res
      this.$message.success('获取指标体系信息成功!')
    },
    // 根据指标体系名查看指标树
    async findIndexSystemByName(name) {
      const { data: res } = await this.$http.get('/generator/indexsystem/indexSysMes?indexSysName=' + name)
      this.$message.success('获取指标树成功!')
      this.treeData = res.indexSysMes
    },
    // 树形结构数据转单层数组形式
    jsonToArray(nodes) {
      var r = []
      if (Array.isArray(nodes)) {
        for (var i = 0, l = nodes.length; i < l; i++) {
          r.push(nodes[i]) // 取每项数据放入一个新数组
          if (Array.isArray(nodes[i].children) && nodes[i].children.length > 0) {
            r = r.concat(this.jsonToArray(nodes[i].children))
          }
          delete nodes[i].children
        }
      }
      return r
    },
    // 深拷贝
    deepCopy(obj) {
      var object
      // 深度复制数组
      if (Object.prototype.toString.call(obj) === '[object Array]') {
        object = []
        for (var i = 0; i < obj.length; i++) {
          object.push(this.deepCopy(obj[i]))
        }
        return object
      }
      // 深度复制对象
      if (Object.prototype.toString.call(obj) === '[object Object]') {
        object = {}
        for (var p in obj) {
          object[p] = obj[p]
        }
        return object
      }
    },
    // 数组转化
    async changeArry() {
      var copydata = await this.deepCopy(this.treeData)
      var bb = this.jsonToArray(copydata)
      console.log('json转数组', bb)
      // var aa = arrayToJson(data)
      // console.log('数组转树形结构', aa)
    },
    // 删除节点
    deleteNode() {
      this.$refs.tree.remove(this.currentNode)
      flatten(this.treeData)
    },
    // 编辑节点
    editNode() {
      // debugger;
      if (!this.currentData.isEdit) {
        this.$set(this.currentData, 'isEdit', true)
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    // this.test();
    //   拖拽结束后验证后不可拖拽
    // this.treeDataCopy=JSON.parse(JSON.stringify(this.treeData))
  }
}
</script>
<style lang="less" scoped>
.header{
    position: absolute;
    top:15%;
    left: 45%;
}
.buttons{
    position: absolute;
    bottom: 12px;
    left: 55%;
}
.container {
  height: 95%;
  .ct-inner {
    height: 100%;
    position: relative;
    padding-top: 84px;
    .ct-inner-fiexd {
      position: absolute;
      left: 0;
      top: 0;
    }
    .ct-inner-content {
      // overflow: hidden;
        .text {
        font-size: 14px;
      }
      .add {
        cursor: pointer;
        margin-top: 10px;
      }

      .delete {
        margin: 10px 0;
        cursor: pointer;
      }

      .edit {
        margin-bottom: 10px;

        cursor: pointer;
      }

      .box-card {
        width: 140px;

        position: absolute;

        z-index: 1000;
      }
      .slot-t-node--label {
        background-color: #f5f7fa;
      }
    }
  }
}
.span-ellipsis {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: inline-block;
}
.el-tree {
  width: 100%;
  max-height: 95%;
  padding-bottom: 20px;
  overflow: auto;
}
.el-tree > .el-tree-node {
  display: inline-block;
  min-width: 100%;
}
.el-tree-node__content {
  height: 30px;
}
</style>
